<template>
  <div>
    <!--  购买皮肤教程  -->
    <el-dialog
        title="感谢购买DLC"
        :visible.sync="tutorialVisible"
        top="5vh"
        width="85%">
      <el-steps v-if="tutorialStep > 0" :active="tutorialStep - 1" align-center style="margin-bottom: 10px">
        <el-step title="选择皮肤"></el-step>
        <el-step title="复制插件地址"></el-step>
        <el-step title="粘贴导入直播软件"></el-step>
        <el-step title="发送弹幕测试"></el-step>
      </el-steps>
      <div v-if="tutorialStep === null ">
        <span class="tutorial">查看使用购买皮肤的教程？</span>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content bg-purple">
              <el-button @click="tutorialStep = 1 ">第一次使用，看下教程</el-button>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content bg-purple-light">
              <el-button @click="alwaysCloseTutorial">我知道如何使用，不再提示</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <div v-if="tutorialStep === 1">
        <span class="tutorial">点击弹幕皮肤栏，选择购买的皮肤</span>
        <el-image src="https://i1.xuehusang.cn/openlivechat-css/tutorial/olc-1.webp"></el-image>
      </div>
      <div v-if="tutorialStep === 2">
        <span class="tutorial">在插件页底部点击复制URL地址</span>
        <el-image src="https://i1.xuehusang.cn/openlivechat-css/tutorial/olc-2.webp"></el-image>
      </div>
      <div v-if="tutorialStep === 3">
        <span class="tutorial">到直播姬/OBS中粘贴地址</span>
        <el-collapse accordion>
          <el-collapse-item title="直播姬" name="1">
            <span>在直播姬窗口左侧点击添加素材按钮，然后选择浏览器。粘贴上一步复制的地址，调整好合适长宽并点击确定。</span>
            <el-carousel height="400px">
              <el-carousel-item>
                <el-image fit="contain"
                          src="https://i1.xuehusang.cn/openlivechat-css/tutorial/olc-3-2-1.png"></el-image>
              </el-carousel-item>
              <el-carousel-item>
                <el-image fit="contain"
                          src="https://i1.xuehusang.cn/openlivechat-css/tutorial/olc-3-2-2.png"></el-image>
              </el-carousel-item>
            </el-carousel>
          </el-collapse-item>
          <el-collapse-item title="OBS" name="2">
            <span>在OBS的来源窗口中新建浏览器图层，在URL中粘贴上一步复制的地址，调整好合适长宽，请务必滑到下方<strong>勾选“不可见时关闭源”。</strong></span>
            <el-image src="https://i1.xuehusang.cn/openlivechat-css/tutorial/olc-3-1.webp"></el-image>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div v-if="tutorialStep === 4">
        <span class="tutorial">在直播间中发送几条弹幕，测试功能和皮肤是否正常，如遇到问题请B站私信<a
            href="https://message.bilibili.com/#/whisper/mid10983855" target="_blank">与我联系</a></span>
        <el-image src="https://i1.xuehusang.cn/openlivechat-css/tutorial/olc-4.webp"></el-image>
      </div>
      <div v-if="tutorialStep === 5">
        <span class="tutorial">皮肤设置完成，以后每次开播打开直播软件便会自动加载弹幕姬，无需重复操作<br/>如果后续需要换皮肤或改设置，重新复制粘贴下新的URL地址替换原来源图层的即可</span>
      </div>
      <span slot="footer" class="dialog-footer" v-if="tutorialStep > 0">
    <el-button @click="tutorialStep --" v-show="tutorialStep > 1">上一步</el-button>
    <el-button type="primary" @click="tutorialStep ++" v-show="tutorialStep <= 4">下一步</el-button>
    <el-button type="primary" @click="alwaysCloseTutorial" v-show="tutorialStep > 4">完成</el-button>
  </span>
    </el-dialog>
    <p style="margin-top: 2px;margin-bottom: 10px;">
      <el-form ref="form" :model="form" :rules="{
        roomId: [
          {required: true, message: $t('home.roomIdEmpty'), trigger: 'blur'},
          {type: 'integer', min: 1, message: $t('home.roomIdInteger'), trigger: 'blur'}
        ]
      }" label-width="150px">
        <el-alert
            center
            style="margin-bottom: 5px;"
            type="warning">
          <template #title>
            {{ $t('home.alert') }}
            <!--            <el-link :href="$router.resolve({name: 'captainFx'}).href" type="primary">-->
            <!--              <i class="el-icon-view"></i>-->
            <!--              前往-->
            <!--            </el-link>-->
          </template>
        </el-alert>
        <el-tabs type="border-card">
          <el-tab-pane :label="$t('home.general')">
            <el-row :gutter="20">
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item :label="$t('home.showDanmaku')">
                  <el-switch v-model="form.showDanmaku"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item :label="$t('home.showSuperchat')">
                  <el-switch v-model="form.showSuperchat"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item :label="$t('home.showNewMember')">
                  <el-switch v-model="form.showNewMember"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item :label="$t('home.showGift')">
                  <el-switch v-model="form.showGift"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item>
                  <template slot="label">
                    {{ $t('home.showGiftInfo') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.showGameInfoTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-switch v-model="form.showGiftInfo"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item>
                  <template slot="label">
                    {{ $t('home.showLike') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.showLikeTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-switch v-model="form.showLike"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider v-if="translationAuthority"></el-divider>
            <el-row :gutter="20" v-if="translationAuthority">
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-badge value="beta" class="item">
                  <el-form-item :label="$t('home.activeTranslate')">
                    <el-switch v-model="form.translateActive"></el-switch>
                  </el-form-item>
                </el-badge>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item :label="$t('home.targetLang')">
                  <el-select v-model="form.targetLanguage" :disabled="!form.translateActive" placeholder="翻译至">
                    <el-option
                        v-for="item in languageOption"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item>
                  <template slot="label">
                    {{ $t('home.onlyShowTranslate') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.onlyShowTranslateTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-switch v-model="form.onlyShowTranslate" :disabled="!form.translateActive"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item :label="$t('home.translateSuperChat')">
                  <el-switch v-model="form.scTranslate" :disabled="!form.translateActive"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider></el-divider>
            <el-row :gutter="20">
              <el-col :sm="7" :xs="12" style="height: 40px;" :id="foreignLayout()">
                <el-form-item :label="$t('home.danmakuAtBottom')">
                  <el-switch v-model="form.danmakuAtBottom"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;" :id="foreignLayout()">
                <el-form-item>
                  <template slot="label">
                    {{ $t('home.tickerAtButtom') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.tickerAtButtomTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-switch v-model="form.tickerAtButtom"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :sm="7" :xs="12" style="height: 40px;" :id="foreignLayout()">
              <el-form-item>
                  <template slot="label">
                    {{ $t('home.mergeSimilarDanmaku') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content">
                        <div v-html="$t('home.mergeSimilarDanmakuTip')"></div>
                        <el-image fit="contain"
                                  src="https://i1.xuehusang.cn/openlivechat-css/image/QQ20240222-0016542x.png"
                                  style="height: 35px;"/>
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-switch v-model="form.mergeSimilarDanmaku"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :sm="7" :xs="12" style="height: 40px;">
                <el-form-item>
                  <template slot="label">
                    {{ $t('home.mergeGift') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.mergeGiftTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-switch v-model="form.mergeGift"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :sm="7" :xs="12" style="height: 40px;" :id="foreignLayout()">
                <el-form-item>
                  <template slot="label">
                    {{ $t('home.userNameBlur') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.userNameBlurTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-switch v-model="form.userBlur"></el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :sm="8" :xs="12" :id="foreignLayout()">
                <el-form-item>
                  <template slot="label">
                    {{ $t('home.minGiftPrice') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.minGiftPriceTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-input v-model.number="form.minGiftPrice" min="0" size="medium" type="number">
                    <template slot="suffix">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :sm="8" :xs="12" :id="foreignLayout()">
                <el-form-item label-width="185px">
                  <template slot="label">
                    {{ $t('home.minTickerPrice') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.minTickerPriceTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-input v-model.number="form.minTickerPrice" min="0.1" size="medium" type="number">
                    <template slot="suffix">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :sm="8" :xs="12" :id="foreignLayout()">
                <el-form-item>
                  <template slot="label">
                    {{ $t('home.maxNumber') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.maxNumberTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-input v-model.number="form.maxNumber" min="1" size="medium" type="number">
                    <template slot="suffix">条</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :sm="8" :xs="12" :id="foreignLayout()">
                <el-form-item :label="$t('home.fadeOutNum')">
                  <el-input v-model.number="form.fadeOutNum" min="1" size="medium" type="number">
                    <template slot="suffix">条</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :sm="8" :xs="12">
                <el-form-item :id="foreignLayout()">
                  <template slot="label">
                    {{ $t('home.pinTime') }}
                    <el-tooltip :enterable="false" placement="top">
                      <div slot="content" v-html="$t('home.pinTimeTip')">
                      </div>
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-input v-model.number="form.pinTime" min="1" size="medium" type="number">
                    <template slot="suffix">秒</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :sm="8" :xs="12">
                <el-form-item>
                  <template slot="label">
                    {{ $t('home.bigEmoticonSize') }}
                    <el-tooltip :enterable="false" content="修改除了小emoji 所有大表情的尺寸" placement="top">
                      <i class="el-icon-info"></i>
                    </el-tooltip>
                  </template>
                  <el-input v-model.number="form.emoticonSize" min="1" size="medium" type="number">
                    <template slot="suffix">px</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane :label="$t('home.skin')">
            <el-row :gutter="20">
              <el-col :xs="16" :sm="16" :md="16" :lg="16" :xl="16">
                <div id="example-container" :class="{light: true}">
                  <!--                  <p style="font-size: 5pt;margin: 0 auto;text-align: center">{{ $t('home.previewWarning') }}</p>-->
                  <div id="fakebody" style="zoom: 0.5;">
                    <room ref="room"></room>
                  </div>
                </div>
              </el-col>
              <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8"
                      style="max-height: 500px !important;overflow-y: scroll;padding-left: 0px;padding-right: 0px;overflow-x: hidden;">
                <div v-for="(item,index) in skinList">
                  <el-button :id="index"
                             v-model="form.skin"
                             :class="item.thumb !== '' ? 'stylesheet-button with-pic' : 'stylesheet-button'"
                             :label="item.id"
                             border
                             @click="applySkin(item.id,item.url,index)"
                  >
                    <div style="margin-bottom: 1px;">{{ item.name }}</div>
                    <div style="margin-bottom: 3px;width: 100%">{{ item.author }}</div>
                    <el-image
                        v-if="item.thumb !== ''"
                        :src="item.thumb"
                        fit="contain"
                        style="width: 100%;border-radius: 4px;"
                    ></el-image>
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane :label="$t('home.block')">
            <el-row :gutter="20">
              <el-col :sm="12" :xs="24">
                <el-form-item :label="$t('home.blockMedalLevel')">
                  <el-slider v-model="form.blockMedalLevel" :max="40" :min="0" show-input></el-slider>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item :label="$t('home.blockKeywords')">
              <el-input v-model="form.blockKeywords" :placeholder="$t('home.onePerLine')" :rows="5"
                        type="textarea"></el-input>
            </el-form-item>
            <el-form-item :label="$t('home.blockUsers')">
              <el-input v-model="form.blockUsers" :placeholder="$t('home.onePerLine')" :rows="5"
                        type="textarea"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane :label="$t('home.testing')">
            <el-row :gutter="20">
              <el-col :sm="12" :xs="24">
                <el-form-item :label="$t('home.minDanmakuInterval')">
                  <el-slider v-model="form.minDanmakuInterval" :max="5000" :min="35"
                             show-input></el-slider>
                </el-form-item>
              </el-col>
              <el-col :sm="12" :xs="24">
                <el-form-item :label="$t('home.maxDanmakuInterval')">
                  <el-slider v-model="form.maxDanmakuInterval" :max="5000" :min="35"
                             show-input></el-slider>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </p>
    <el-card :body-style="{border: '2px solid #409EFF'}">
      <el-row :gutter="0">
        <el-col :span="4" style="display: grid;justify-items: center;">
          <el-image
              :src="this.account_info.uface"
              fit="fill"
              style="width: 64px; height: 64px;border-radius: 50%;margin-bottom: 4px;">
            <div slot="error" class="image-slot">
              <el-image
                  fit="fill"
                  src=""
              />
            </div>
          </el-image>
          <div>{{ this.account_info.uname }}</div>
        </el-col>
        <el-col :span="1">
          <el-divider direction="vertical"></el-divider>
        </el-col>
        <el-col :span="19">
          <el-form :model="form" label-width="80px">
            <el-popover
                v-model="tips_visible"
                :content="$t('home.settingsChangeTipsContent')"
                :title="$t('home.settingsChangeTipsTitle')"
                placement="top-start"
                trigger="manual"
                width="160">
              <el-form-item slot="reference" style="margin-bottom: 0;">
                <template slot="label">
                  <strong>{{ $t('home.roomUrl') }}</strong>
                </template>
                <el-input ref="roomUrlInput" :value="obsRoomUrl" readonly
                          style="width: calc(100% - 6em); margin-right: 0.6em;"></el-input>
                <el-button type="primary" @click="copyUrl">{{ $t('home.copy') }}</el-button>
              </el-form-item>
            </el-popover>
            <el-form-item style="margin-top: 10px;margin-bottom: 0;">
              <el-button @click="copyUrl2">
                {{ $t('home.copyTestUrl') }}
                <el-tooltip :enterable="false" placement="top">
                  <div slot="content" v-html="$t('home.copyTestUrlTip')"></div>
                  <i class="el-icon-info"></i>
                </el-tooltip>
              </el-button>
              <el-button @click="tutorialVisible = true;tutorialStep = 1 " style="margin-left: 5px;">DLC皮肤使用教程
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
import * as chatConfig from '@/api/chatConfig'
import Room from "@/views/Room.vue";
import axios from "axios";

export default {
  name: 'Home',
  components: {Room},
  data() {
    let styleElement = document.createElement('style')
    styleElement.setAttribute("id", "skin")
    document.head.appendChild(styleElement)
    return {
      serverConfig: {
        enableTranslate: true,
        loaderUrl: ''
      },
      form: {
        ...chatConfig.getLocalConfig()
      },
      styleElement,
      selected_skin_button_id: 0,
      tips_visible: false,
      pay_skin_list: [],
      account_info: {},
      // 以下两个是国内无cf防火墙接口的Base64加密
      retryHock: 'aHR0cHM6Ly9vbGMtY24ueHVlaHVzYW5nLmNuL29wZW5saXZlY2hhdC9zdGFydA==',
      closeHock: 'aHR0cHM6Ly9vbGMtY24ueHVlaHVzYW5nLmNuL29wZW5saXZlY2hhdC9jbG9zZQ==',
      game_id: '',
      tutorialVisible: false,
      tutorialStep: null,
      activeName: '1',
      languageOption: [{
        value: 'en',
        label: 'English'
      }, {
        value: 'jp',
        label: '日本語'
      }, {
        value: 'ko',
        label: '한국인'
      }, {
        value: 'fr',
        label: 'Français'
      }, {
        value: 'id',
        label: 'Indonesia'
      }],
      translationAuthority: false
    }
  },
  created() {
    // 【非常重要】如果用户直接通过直播姬添加了插件，B站会在url params中增加plug_env参数为0，检测到直接跳转到实际弹幕插件页面，而非设置页
    // https://open-live.bilibili.com/document/ad4901b8-c13e-7a20-e07e-410ad182564a#h1-u5FEBu901Fu5F00u59CB
    if (this.$route.query.plug_env == "0") {
      const user_data = {
        "code": this.$route.query.Code,
        "mid": this.$route.query.Mid,
        "timestamp": this.$route.query.Timestamp,
        "sign": this.$route.query.CodeSign
      }
      const {code, mid, sign, timestamp} = user_data;
      if (code !== undefined) {
        this.form.Code = code;
      }
      if (mid !== undefined) {
        this.form.Mid = mid;
      }
      if (sign !== undefined) {
        this.form.CodeSign = sign;
      }
      if (timestamp !== undefined) {
        this.form.Timestamp = timestamp;
      }
      this.form['plug_env'] = "0"
      this.$router.push({
        path: '/room/open-live', query: this.form
      })
    } else {
      // 广告，通用element-ui的notify组件
      this.$notify({
        title: 'DLC皮肤上线啦!',
        message: '多款个性皮肤,快来选购吧',
        position: 'bottom-left',
        duration: 3500,
        iconClass: 'el-icon-shopping-cart-2'
      });
    }
  },
  computed: {
    roomUrl() {
      return this.getRoomUrl(false)
    },
    obsRoomUrl() {
      if (this.roomUrl === '') {
        return ''
      }
      if (this.serverConfig.loaderUrl === '') {
        return this.roomUrl
      }
      let url = new URL(this.serverConfig.loaderUrl)
      // url.searchParams.append('Code', this.$route.query.Code || 0)
      url.searchParams.append('url', this.roomUrl)
      return url.href
    },
    skinList() {
      // 预设免费可用的皮肤list，皮肤名接入了vue-i18n
      let default_skin = [{
        "url": "",
        "id": "none",
        "name": this.$t("home.skinList['none']"),
        "thumb": ""
      },
        {
          "url": "https://i1.xuehusang.cn/openlivechat-css/openlivechat.css",
          "id": "openlivechat",
          "author": "兔宝的神奇口袋",
          "name": this.$t("home.skinList['openlivechat']"),
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/openlivechat.jpg"
        },
        {
          "id": "default",
          "url": "https://i1.xuehusang.cn/openlivechat-css/default.css",
          "name": this.$t("home.skinList['default']"),
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/default.jpg"
        },
        {
          "id": "1125-candy-game-all-in",
          "url": "https://i1.xuehusang.cn/openlivechat-css/1125-candy-game-all-in.css",
          "name": this.$t("home.skinList['1125-candy-game-all-in']"),
          "author": "兔宝的神奇口袋",
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/1125-candy-game-all-in.jpg"
        },
        {
          "url": "https://i1.xuehusang.cn/openlivechat-css/A45%E9%AD%94%E5%A5%B3%E8%8A%B1%E5%AB%81light.css",
          "id": "monvhuajia-light",
          "name": this.$t("home.skinList['monvhuajia-light']"),
          "author": "槐夏虫眠",
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/monvhuajia-light.jpg"
        },
        {
          "url": "https://i1.xuehusang.cn/openlivechat-css/A45%E9%AD%94%E5%A5%B3%E8%8A%B1%E5%AB%81night.css",
          "id": "monvhuajia-night",
          "name": this.$t("home.skinList['monvhuajia-night']"),
          "author": "槐夏虫眠",
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/monvhuajia-night.jpg"
        }
      ]
      return this.pay_skin_list.concat(default_skin)
    },
    // 检测当前选择的语言
    useLanguage: function () {
      return this.$t('sidebar.home') === '首页' ? 'zh' : 'notZH'
    }
  },
  watch: {
    roomUrl: _.debounce(function () {
      window.localStorage.roomId = this.form.roomId
      // this.form.imageShowType.value = this.form.imageShowType.value.id
      let real_form = this.form
      // console.log(this.$refs.imageShowTypeInput.value)
      // real_form.imageShowType.value = this.$refs.imageShowTypeInput.value
      this.popoverTipsCountdown()
      chatConfig.setLocalConfig(real_form)
    }, 500)
  },
  mounted() {
    this.serverConfig = {
      "enableTranslate": false,
      "loaderUrl": ""
    }
    this.user_data = {
      "code": this.$route.query.Code,
      "mid": this.$route.query.Mid,
      "timestamp": this.$route.query.Timestamp,
      "sign": this.$route.query.CodeSign
    }
    const {code, mid, sign, timestamp} = this.user_data;
    if (code !== undefined) {
      this.form.Code = code;
    }
    if (mid !== undefined) {
      this.form.Mid = mid;
    }
    if (sign !== undefined) {
      this.form.CodeSign = sign;
    }
    if (timestamp !== undefined) {
      this.form.Timestamp = timestamp;
    }
    if (this.$route.query.plug_env !== "0") {
      this.checkAccountInfo()
    }
    //   检测已选中的皮肤选择，添加hover状态
    const onselect_button = document.getElementById(this.selected_skin_button_id)
    onselect_button.classList.add("skin-button-select")
    if (this.$route.query.plug_env !== "0") {
      this.$refs.room.start()
    }
  },
  methods: {
    getRoomUrl(isTestRoom) {
      if (isTestRoom && this.form.roomId === '') {
        return ''
      }
      let query = {...this.form}
      // 针对uri规则换行符从%0A变为%250A
      query.blockKeywords = encodeURIComponent(query.blockKeywords)
      query.blockUsers = encodeURIComponent(query.blockUsers)
      delete query.roomId
      let resolved
      if (isTestRoom) {
        resolved = this.$router.resolve({name: 'test_room', query})
      } else {
        resolved = this.$router.resolve({name: 'room', params: {roomId: this.form.roomId}, query})
      }
      return `${window.location.protocol}//${window.location.host}${resolved.href}`
    },
    copyUrl() {
      this.$refs.roomUrlInput.select()
      document.execCommand('Copy')
    },
    copyUrl2() {
      const oInput = document.createElement('input');
      document.body.appendChild(oInput)
      oInput.value = this.getRoomUrl(true);
      document.body.appendChild(oInput);
      oInput.select();
      document.execCommand('Copy');
      document.body.removeChild(oInput)
    },
    applySkin(skin_id, skin_url, onselect_skin_button_id) {
      const selected_button = document.getElementById(this.selected_skin_button_id)
      selected_button.classList.remove("skin-button-select")
      this.styleElement.innerText = ''
      this.styleElement.innerText = "@import url('" + skin_url + "');"
      const onselect_button = document.getElementById(onselect_skin_button_id)
      onselect_button.classList.add("skin-button-select")
      this.form.skin = skin_id
      this.selected_skin_button_id = onselect_skin_button_id
    },
    popoverTipsCountdown() {
      if (this.tips_visible === false) {
        this.tips_visible = true
        setTimeout(() => {
          this.tips_visible = false
        }, 4000)
      }
    },
    // 加载页面时会请求一次start，为了识别用户是谁（用户只会传递身份码）
    async checkAccountInfo() {
      let res
      await axios.post('https://olc.xuehusang.cn/openlivechat/start', {
        "code": this.$route.query.Code,
        "mid": this.$route.query.Mid,
        "timestamp": this.$route.query.Timestamp,
        "sign": this.$route.query.CodeSign
      }).then(response => {
        res = response.data
      })
          .catch(async error => {
            if (error.message.includes('Network Error') || error.message.includes('timeout')) {
              try {
                await axios.post(atob(this.retryHock), {
                  "code": this.$route.query.Code,
                  "mid": this.$route.query.Mid,
                  "timestamp": this.$route.query.Timestamp,
                  "sign": this.$route.query.CodeSign
                }).then(response => {
                  res = response.data
                })
              } catch {
                this.$notify({
                  title: '获取用户信息失败',
                  message: '请注意已购的DLC皮肤无法加载，其他功能不受影响',
                  duration: 0,
                  type: 'warning'
                });
                return
              }
              this.gfwBlock = true
            } else {
              console.error('Network request error:', error.message);
            }
          })
      if (res.code == 0) {
        // 主页显示用户信息
        this.account_info = res.anchor_info
        this.game_id = res.game_id
        // 如果是购入了皮肤的用户，导入皮肤列表
        if (res.skin_list !== undefined) {
          this.pay_skin_list = res.skin_list
          if (!localStorage.getItem('skinTutorial')) {
            this.tutorialVisible = true
          }
        }
        // 如果返回的user_function字段里有translate，显示翻译选项面板
        if (res.user_function.includes('translate')) {
          this.translationAuthority = true
        }
        await this.closeOpenLiveClient()
      }
    },
    // 关闭当前场次连接，因为一次start后的心跳多开为5个，周期3分钟，加载检测用户身份后立即关闭清除掉占用名额
    async closeOpenLiveClient() {
      await axios.post('https://olc.xuehusang.cn/openlivechat/close', {
        "game_id": this.game_id
      }).then(response => {
      })
          .catch(async error => {
            if (error.message.includes('Network Error') || error.message.includes('timeout')) {
              try {
                await axios.post(atob(this.closeHock), {
                  "game_id": this.game_id
                }).then(response => {
                })
              } catch {
                return
              }
              this.gfwBlock = true
            } else {
              console.error('Network request error:', error.message);
            }
          })
    },
    // 一个不再提示已购dlc教程的本地缓存检测
    alwaysCloseTutorial() {
      this.tutorialVisible = false
      localStorage.setItem('skinTutorial', '1');
    },
    // 因为外语显示会有排版问题，如果不是中文会在dom里加上一个外语的css调整布局
    foreignLayout() {
      if (this.useLanguage === 'zh') {
        return null
      } else {
        return 'foreignLayout'
      }
    }
  },
  beforeDestroy() {
    document.head.removeChild(this.styleElement)
  }
}
</script>

<style scoped>
#fakebody {
  outline: 1px #999 dashed;
  height: 100%;
}

#example-container {
  height: 500px;

  background-color: #444;
  background-image: -moz-linear-gradient(45deg, #333 25%, transparent 25%),
  -moz-linear-gradient(-45deg, #333 25%, transparent 25%),
  -moz-linear-gradient(45deg, transparent 75%, #333 75%),
  -moz-linear-gradient(-45deg, transparent 75%, #333 75%);
  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.25, #333), color-stop(.25, transparent)),
  -webkit-gradient(linear, 0 0, 100% 100%, color-stop(.25, #333), color-stop(.25, transparent)),
  -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.75, transparent), color-stop(.75, #333)),
  -webkit-gradient(linear, 0 0, 100% 100%, color-stop(.75, transparent), color-stop(.75, #333));

  -moz-background-size: 32px 32px;
  background-size: 32px 32px;
  -webkit-background-size: 32px 32px;

  background-position: 0 0, 16px 0, 16px -16px, 0px 16px;

  overflow: hidden;
}

#example-container.light {
  background-color: #ddd;
  background-image: -moz-linear-gradient(45deg, #eee 25%, transparent 25%),
  -moz-linear-gradient(-45deg, #eee 25%, transparent 25%),
  -moz-linear-gradient(45deg, transparent 75%, #eee 75%),
  -moz-linear-gradient(-45deg, transparent 75%, #eee 75%);
  background-image: -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.25, #eee), color-stop(.25, transparent)),
  -webkit-gradient(linear, 0 0, 100% 100%, color-stop(.25, #eee), color-stop(.25, transparent)),
  -webkit-gradient(linear, 0 100%, 100% 0, color-stop(.75, transparent), color-stop(.75, #eee)),
  -webkit-gradient(linear, 0 0, 100% 100%, color-stop(.75, transparent), color-stop(.75, #eee));
}

.stylesheet-button {
  width: 100%;
  margin: 5px 0 !important;
}

.stylesheet-button.with-pic {
  height: 100%;
  user-select: none;
}

.skin-button-select {
  color: #409EFF;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.el-divider--vertical {
  height: 90px;
}

.tutorial {
  font-size: 20px;
  margin-bottom: 10px;
}

div .el-form::v-deep .el-form-item__label {
  white-space: pre-line !important;
  line-height: 40px;
}
#foreignLayout {
  line-height: 10px;
  height: 50px !important;
}
#foreignLayout::v-deep .el-form-item__label{
  line-height: 22px;
}

</style>